<?php
namespace app\common\logic;


class RoleLogic
{

	private function M()
	{
		return M('role');
	}
	
	public function ls()
	{
		$data = $this->M()->order('px ASC')->select();
		return $data;
	}

	public function map()
	{
		$data = $this->M()->order('px ASC')->column('name,role');   //如果id为键,前端会自动按id排序
		return $data;
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->M()->find($id);
		$row['pri'] = $row['pri'] ? json_decode($row['pri'], true) : array();
		return $row;
	}

	public function save($post)
	{
		$id = (int) $post['id'];
		foreach($post['pri'] as &$p) {
			if($p[0] == '/') $p = substr($p, 1, 99);
		}
		$post['pri'] = array_filter($post['pri']);
		$post['pri'] = array_values($post['pri']);
		$post['pri'] = json_encode($post['pri']);
		//允许编辑字段
		if($id) {
			$rs = $this->M()->where('id', $id)->update($post);
		}else{
			$rs = $this->M()->insert($post);
		}
		if($rs !== false) {
			return true;
		}else{
			error('保存错误');
		}
	}

	//修改状态
	public function st($id, $st)
	{
		$rs = $this->M()->where('id', $id)->setField('st', $st);
		if($rs !== false) {
			return true;
		}else{
			error('修改状态错误');
		}
	}

	/**
	 * 排序
	 * @param $ids  array(3,2,40)
	 */
	public function px($ids)
	{
		foreach($ids as $k => $id) {
			$id = (int) $id;
			if(!$id) continue;
			$rs = $this->M()->where('id', $id)->setField('px', $k + 1);
			if($rs === false) error('保存顺序错误');
		}
		return true;
	}
}